<?php

use app\admin\model\CashcardCate;
use app\admin\model\CashcardUser;

/**
 * Class CashcardHandler 接口操作代金券逻辑类
 * Author FashionJune
 */
class CashcardHandler
{
    protected $CashcardCate;
    protected $CashcardUser;

    public function __construct()
    {
        $this->CashcardCate = CashcardCate::init();
        $this->CashcardUser = CashcardUser::init();
    }

    /**
     * @title 检查权限
     * @param int $admin_id
     * @param mixed $admin_ids
     * @author FashionJune
     */
    public function adminPermissionCheck(int $admin_id, $admin_ids)
    {
        if (is_numeric($admin_ids)) {//传入的是cate_id
            $admin_ids = $this->CashcardCate->where('id', $admin_ids)->value('card_author');
        }
        $admin_ids = str2arr($admin_ids);
        return in_array($admin_id, $admin_ids);
    }

    /**
     * @title 检查限额
     * @author FashionJune
     * @param int $admin_id
     * @param int $cate_id
     * @param mixed $cate_quota
     */
    public function adminQuotaCheck(int $admin_id, int $cate_id, $cate_quota = null)
    {
        if (!$cate_quota) {
            $cate_quota = $this->CashcardCate->where('id', $cate_id)->value('num_person');
        }
        //TODO
        $sended_num = $this->CashcardUser->where('');
    }


    /**
     * @title 获取卡券包二维码页面
     * @param int $admin_id
     * @param int $cate_id
     * @author FashionJune
     */
    public function beforeSend(int $admin_id, int $cate_id)
    {
        //获取代金券分组信息
        $cate_info = $this->CashcardCate->find($cate_id);
        (!$cate_info) && api_error('代金券信息获取失败');
        (!$cate_info['num']) && api_error('代金券信息获取失败');
        //检查权限
        $this->adminPermissionCheck($admin_id, $cate_info['card_author']) && api_error('没有分发权限');
        //剩余数量检查

        //检查限额
        $this->adminQuotaCheck($admin_id, $cate_id, $cate_info['num_person']) && api_error('没有剩余可用代金券');
    }


    /**
     * @title 管理员分发券给消费者
     * @author FashionJune
     * @param int $admin_id
     * @param int $user_id
     * @param int $cate_id
     * @param int $num
     */
    public function adminSendToUser(int $admin_id, int $user_id, int $cate_id, int $num = 1)
    {

    }

}